{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from gs_quant.markets.portfolio import Portfolio\n",
    "from gs_quant.instrument import IRSwaption\n",
    "from gs_quant.risk import IRVega, IRDelta, Price\n",
    "from gs_quant.markets import HistoricalPricingContext, PricingContext\n",
    "import datetime as dt\n",
    "import pandas as pd\n",
    "\n",
    "pd.options.display.float_format = '{:,.0f}'.format"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# instantiate session if not running in jupyter hub\n",
    "from gs_quant.session import GsSession\n",
    "GsSession.use(client_id=None, client_secret=None, scopes=('run_analytics',)) "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Extract instruments "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "with PricingContext(pricing_date=dt.date(2019, 4, 24)):\n",
    "    trade1=IRSwaption(pay_or_receive='Pay', notional_currency='EUR', expiration_date='6m', termination_date='3y', strike='ATMF', name='payer')\n",
    "    trade2=IRSwaption(pay_or_receive='Receive', notional_currency='EUR', expiration_date='6m', termination_date='3y', strike='ATMF+50', name='receiver')\n",
    "    trade2.resolve()\n",
    "portfolio = Portfolio((trade1, trade2))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# We can reference the instruments in the portfolio in different ways \n",
    "print(portfolio[1]) # by index\n",
    "print(portfolio[trade2])  # by instrument object - - note instrument object changes once you resolve it\n",
    "print(portfolio['receiver'])  # by instrument name"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Extract risk results"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "with PricingContext(pricing_date=dt.date(2019, 4, 24)):\n",
    "    results = portfolio.calc((IRVega, IRDelta, Price))\n",
    "type(results)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# we can extract all the risks for a single trade and it will return a dictionary of results keyed by the risk type\n",
    "# note that the risks can come back as a number of formats depending on what the risk is.  So it could come back as a\n",
    "# scalar float or as a panda series or as a panda dataframe\n",
    "results[0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# we can extract a single risk for a single trade in a number of ways\n",
    "print('{:,.0f}'.format(results[Price]['receiver'])) # by risk name and trade name\n",
    "print('{:,.0f}'.format(results[Price][1])) # by risk name and index of trade in portfolio\n",
    "print('{:,.0f}'.format(results[Price][trade2])) # by risk name and trade object\n",
    "\n",
    "# order doesn't matter when extracting results from a PorfolioRiskResult\n",
    "print('{:,.0f}'.format(results['receiver'][Price]))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# we can aggregate risks\n",
    "a = results[Price]['payer']\n",
    "b = results[Price]['receiver']\n",
    "print('{:,.0f}'.format(a + b))\n",
    "print('{:,.0f}'.format(results[Price].aggregate()))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# we could return the results as a dataframe\n",
    "pd.DataFrame(results[Price])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# if the risk is not scalar as in the case of IRDelta we can use a similar pattern but the result will be a dataframe\n",
    "results[IRDelta]['payer']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# if we wanted to see the total IRDelta for this trade we could do\n",
    "results[IRDelta]['payer'].value.sum()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# we can aggregate dataframe results\n",
    "print('{:,.0f}'.format(results[IRDelta][0].value[1]))\n",
    "print('{:,.0f}'.format(results[IRDelta][1].value[1]))\n",
    "results[IRDelta].aggregate()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# when we price with an HistoricalPricingContext we introduce a new dimension to our results\n",
    "\n",
    "with HistoricalPricingContext(dt.date(2019, 4, 24), dt.date(2019, 5, 24)):\n",
    "    hist_results = portfolio.calc((IRVega, IRDelta, Price))\n",
    "\n",
    "type(hist_results)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# now if we ask for the price of a single trade instead of a float we will receieve a panda series of floats indexed by date\n",
    "hist_results[Price][trade1]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# we can still aggregate in the same way and the series will be aggregated by date\n",
    "hist_results[Price].aggregate()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# to get a single price for a specific date we can do\n",
    "hist_results[Price].aggregate().at[dt.date(2019, 4, 30)]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# if we return a dataframe then the result will be concatinated with an index of the date.\n",
    "hist_results[IRDelta][0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
